const express = require("express");
const pool = require("../pool.js");
const r = express.Router();
const svgCaptcha = require("svg-captcha");
const multer= require('multer');//图片上传
const uuid=require('uuid')   //成一个理论上不重复的128位16进制表示的数字
const fs=require('fs');
//第三方图形验证码模块:
//下载  npm i svg-captcha

//第三方图形验证码模块:
//下载  npm i svg-captcha
r.get("/code", (req, res) => {
  //第二个版本:算术计算
  const cap = svgCaptcha.createMathExpr({
    fontSize: 45,
    mathMin: 1,
    mathMax: 9,
    mathOperator: "+-",
    width: 110,
    height: 45,
    color: true,
  });
  req.session.captcha = cap.text; // session 存储验证码数值
 
  console.log(req.session);
  res.type("svg"); // 响应的类型
  res.send(cap.data);

});

// 用户注册 post /register
r.post("/register", (req, res) => {
  console.log(req.session);
  var obj = req.body;
  let nike_name=obj.uname+Math.floor(Math.random()*1000)
  console.log(obj);
  // 验证验证码
  console.log("验证码", req.session);
  if (obj.code != req.session.captcha) {
    console.log(obj.code);
    console.log(req.session.captcha);
    // res.send("-1");
    res.send({
      code: -1,
      msg: "验证码错误",
    });
    return;
  }

  // 判断用户名是否为空
  if (!obj.uname) {
    res.send({
      code: 201,
      msg: "用户名不能为空",
    });
    return;
  }
  // 判断用户名是否为空
  if (!obj.upwd) {
    res.send({
      code: 201,
      msg: "密码不能为空",
    });
    return;
  }

  // 验证用户名是否存在
  let sql = "select count(uname) as count from user where uname=?";
  pool.query(sql, [obj.uname], (err, result) => {
    if (err) throw err;
    // 查询结果为0表示该用户名不存在 可以执行注册
    if (result[0].count == 0) {
      // 执行注册
      let sql =
        "insert into user values(null,?,?,default,?,default,default,null,null)";
      pool.query(sql, [obj.uname, obj.upwd,nike_name], (err, result) => {
        if (err) throw err;
        res.send({
          code: 200,
          msg: "注册成功",
        });
      });
    } else {
      // 用户名存在返回的结果
      res.send({
        code: 201,
        msg: "该用户名已存在,请重新输入",
      });
    }
  });
});

// 用户登录  post /login
r.post("/login", (req, res) => {
  let obj = req.body;

  if (obj.code != req.session.captcha) {
    console.log(obj.code);
    console.log(req.session.captcha);
    // res.send("-1");
    res.send({
      code: -1,
      msg: "验证码错误",
    });
    return;
  }
  // 判断该用户输入的用户名和密码是否正确
  let sql = "select count(uid) as uid,nick_name,avatar from user where uname=? and upwd=?";
  pool.query(sql, [obj.uname, obj.upwd], (err, result) => {
    if (err) throw err;
    //console.log(result)
    // 正确返回1  错误返回0
    if (result[0].uid == 1) {
      // req.seesion.auth=true;
      res.send({
        code: 200,
        msg: "登录成功",
        data:result
      });
    } else {
      res.send({
        code: 201,
        msg: "登录失败",
      });
    }
  });
});

// 修改密码 put /update
r.put("/update",(req,res)=>{
    let obj = req.body;
    //console.log(obj);
   if(!req.session.auth){
    res.send({
      code: 201,
      msg: "未登录，请先登录",
    });
    return;
   }
  // 判断密码是否为空
  if (!obj.upwd || !obj.upwd2) {
    res.send({
      code: 201,
      msg: "密码不能为空",
    });
    return;
  }

  // 判断两次密码输入是否一致
  if (obj.upwd == obj.upwd2) {
    // 两次密码一致执行修改密码
    let sql = "update user set upwd=? where uid=?";
    pool.query(sql, [obj.upwd, obj.uid], (err, result) => {
      if (err) throw err;
      //console.log(result);
      res.send({
        code: 200,
        msg: "密码修改成功",
      });
    });
  } else {
    res.send({
      code: 202,
      msg: "两次密码不一致",
    });
  }
});

// 修改资料 put /alter 要求必须提供用户的uid
r.put("/alter", (req, res) => {
  let obj = req.body;
  //console.log(obj);

  if (!obj.uid) {
    res.send({
      code: 201,
      msg: "请提供用户id",
    });
    return;
  }

  let sql = "update user set sex=?,nick_name=?,intro=? where uid=?";
  pool.query(
    sql,
    [obj.sex, obj.nick_name, obj.intro, obj.uid],
    (err, result) => {
      if (err) throw err;
      //console.log(result);
      res.send({
        code: 200,
        msg: "修改成功",
      });
    }
  );
});

//接收上传头像并保存数据
const avatar=multer.diskStorage({
  destination:(req,file,cb)=>{
    cb(null,'public')
  },
  filename:(req,file,cb)=>{
    let name=file.originalname;
    let ext=name.substr(name.lastIndexOf('.'));
    cb(null,uuid.v4()+'-'+ new Date().getTime() +ext)
  }
});

const uploadTools=multer({
  storage:avatar
});
r.post('/upload',uploadTools.array('avatarFile'),
      (req,res)=>{
       // console.log(req.files);
       // console.log(req.body);
        let obj=JSON.stringify(req.body);
        let obj1=JSON.parse(obj);
        let uname=obj1.uname;
        let path=req.files[0].filename
        //let uname=req.files[0]
        pool.query('select avatar from user where uname=?',[uname],(err,result)=>{
          let fName=(result[0].avatar);
          console.log(fName)
         if(fName!='unnamed.jpg'){
          fs.unlink('public/'+fName,function(error){
            if(error){
                console.log(error);
                return false;
            }
          })
        }
      })
       
        pool.query("update user set avatar=? where uname=?",[path,uname],(err,result)=>{
          res.send({msg:'ok',data:req.files[0]})
        });
        
      })

module.exports = r;
